package com.kun.ble;

import android.widget.TextView;

import com.kun.utils.DataUtil;

import java.text.DecimalFormat;

/**
 * Created by 荣坤 on 2016/3/24.
 *
 * 解析蓝牙数据
 */
public class BledataUtil {
    public TextView temp_tv,humi_tv,press_tv,battery_tv;
    public static String data_str;
    private byte head;

    /**
     *
     * @param temp_tv 温度
     * @param humi_tv 湿度
     * @param press_tv 大气压
     * @param battery_tv 电量
     */
    public BledataUtil(TextView temp_tv, TextView humi_tv, TextView press_tv, TextView battery_tv){
        this.temp_tv = temp_tv;
        this.humi_tv = humi_tv;
        this.press_tv = press_tv;
        this.battery_tv = battery_tv;
    }

    /**
     *
     * @param data 蓝牙接收到的数据
     */
    public void set(byte[] data){
        if (data == null || data.length == 0) {
            return;
        }
        data_str = DataUtil.getStringByBytes(data);
        if (data_str.length() == 4){
            int bat = (Integer.valueOf(data_str,16)-1010)*10/25;
            battery_tv.setText(""+(bat > 100?100:bat));
            return;
        }else if (data_str.length()!=16){
            return;
        }
        head = data[0];
        switch (head){
            case 0x36:
                if (press_tv!=null) {
                    double pressure = Integer.parseInt(data_str.substring(9), 16) / 1000.0;
                    DecimalFormat df = new DecimalFormat("######0.00");
                    press_tv.setText("" + df.format(pressure));
                }
                break;
            case 0x37:
                if (humi_tv!=null)
                humi_tv.setText(""+ Integer.parseInt(data_str.substring(8,12),16)/10.0);
                break;
            case 0x38:
                if (temp_tv!=null){
                    int a = Integer.parseInt(data_str.substring(8,12),16);
                    if(a>1000){
                        //温度为零下时
                        a = a - 65536;
                    }
                    temp_tv.setText(""+a/10.0);
                }
                break;
            default:
                break;
        }
    }
}
